package org.inet.minispring.resource;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.inet.minispring.exception.InitApplicationContextFailException;

import java.util.Iterator;

/**
 * XML 配置文件的 Resource
 */
public class ClassPathXmlResource implements Resource {

    Iterator<Element> elementIterator;

    public ClassPathXmlResource(String fileName) {
        SAXReader saxReader = new SAXReader();
        var xmlPath = this.getClass().getClassLoader().getResource(fileName);
        // 读取 XML 配置文件
        Document document;
        try {
            document = saxReader.read(xmlPath);
        } catch (DocumentException e) {
            throw new InitApplicationContextFailException("Cannot read XML file：" + fileName);
        }
        Element rootElement = document.getRootElement();
        this.elementIterator = rootElement.elementIterator();
    }

    public boolean hasNext() {
        return this.elementIterator.hasNext();
    }

    public Element next() {
        return this.elementIterator.next();
    }
}
